import { Student } from '../models/Student.js';
import { Class } from '../models/Class.js';
import { MarketingDepartment } from '../models/MarketingDepartment.js';
import { College } from '../models/College.js';
import { DormBuilding } from '../models/DormBuilding.js';
import { Dormitory } from '../models/Dormitory.js';
import { readData, saveData } from '../utils/fileUtils.js';
import path from 'path';
import { fileURLToPath } from 'url';
import XLSX from 'xlsx';
import fs from 'fs';

// 获取当前文件所在目录
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// 学生评语文件路径
const studentCommentsFilePath = path.join(__dirname, '../data/studentComments.json');

const studentModel = new Student();
const classModel = new Class();
const marketingModel = new MarketingDepartment();
const collegeModel = new College();
const dormBuildingModel = new DormBuilding();
const dormitoryModel = new Dormitory();

export class StudentController {
  // 获取学生表单选项数据
  async getFormOptions(req, res) {
    try {
      const marketingDepartments = marketingModel.findAll();
      const classes = classModel.findAll();
      const colleges = collegeModel.findAll();
      const dormBuildings = dormBuildingModel.findAll();

      res.json({
        marketingDepartments: marketingDepartments.map(dept => dept.name),
        classes: classes.map(cls => cls.className),
        colleges: colleges.map(college => college.name),
        dormBuildings: dormBuildings.map(building => building.name)
      });
    } catch (error) {
      console.error('获取学生表单选项失败:', error);
      res.status(500).json({ error: '获取选项数据失败' });
    }
  }

  // 获取学生列表
  async getStudents(req, res) {
    try {
      console.log('获取学生列表，查询参数:', req.query);

      const students = studentModel.findAll();

      // 处理分页
      const page = parseInt(req.query.page) || 1;
      const pageSize = parseInt(req.query.pageSize) || 10;
      const startIndex = (page - 1) * pageSize;
      const endIndex = startIndex + pageSize;

      // 应用搜索过滤
      let filteredStudents = [...students];

      // 关键词搜索
      if (req.query.keyword) {
        const keyword = req.query.keyword.toLowerCase();
        filteredStudents = filteredStudents.filter(student => {
          const name = student.name || '';
          const studentId = student.studentId || '';
          const idCard = student.idCard || '';
          const phone = student.phone || '';
          const className = student.className || '';
          const college = student.college || '';
          const marketingDepartment = student.marketingDepartment || '';

          return name.toLowerCase().includes(keyword) ||
            studentId.toLowerCase().includes(keyword) ||
            idCard.toLowerCase().includes(keyword) ||
            phone.toLowerCase().includes(keyword) ||
            className.toLowerCase().includes(keyword) ||
            college.toLowerCase().includes(keyword) ||
            marketingDepartment.toLowerCase().includes(keyword);
        });
      }

      // 字段精确搜索
      const searchFields = ['name', 'studentId', 'idCard', 'phone', 'className', 'college', 'marketingDepartment', 'dormBuilding', 'dormRoom', 'gender', 'status'];
      searchFields.forEach(field => {
        if (req.query[field] && req.query[field].trim()) {
          const searchValue = req.query[field].toLowerCase();
          filteredStudents = filteredStudents.filter(student => {
            const fieldValue = student[field];
            return fieldValue && fieldValue.toString().toLowerCase().includes(searchValue);
          });
        }
      });

      // 分页
      const paginatedStudents = filteredStudents.slice(startIndex, endIndex);

      // 构建响应
      const response = {
        data: paginatedStudents,
        pagination: {
          current: page,
          pageSize: pageSize,
          total: filteredStudents.length,
          totalPages: Math.ceil(filteredStudents.length / pageSize)
        }
      };

      console.log('返回数据:', {
        dataCount: paginatedStudents.length,
        total: filteredStudents.length,
        pagination: response.pagination
      });

      res.json(response);
    } catch (error) {
      console.error('获取学生列表时出错:', error);
      res.status(500).json({
        error: '服务器内部错误',
        message: error.message
      });
    }
  }

  // 创建学生
  async createStudent(req, res) {
    try {
      const {
        name,
        studentId,
        gender,
        birthDate,
        idCard,
        marketingDepartment,
        className,
        college,
        phone,
        dormBuilding,
        dormRoom,
        status,
        email,
        guardianName,
        guardianPhone,
        guardianRelationship,
        grade,
        major,
        department
      } = req.body;

      console.log('创建学生:', { name, studentId });

      if (!name || !studentId) {
        return res.status(400).json({ error: '姓名和学号为必填字段' });
      }

      const students = studentModel.findAll();
      const classes = classModel.findAll();

      // 检查学号是否已存在
      if (students.find(s => s.studentId === studentId)) {
        return res.status(400).json({ error: '学号已存在' });
      }

      // 验证班级是否存在
      if (className && !classes.find(c => c.className === className)) {
        return res.status(400).json({ error: `班级 "${className}" 不存在` });
      }

      const newStudent = {
        name,
        studentId,
        gender: gender || '',
        birthDate: birthDate || '',
        idCard: idCard || '',
        marketingDepartment: marketingDepartment || '',
        className: className || '',
        college: college || '',
        phone: phone || '',
        dormBuilding: dormBuilding || '',
        dormRoom: dormRoom || '',
        status: status || 'active',
        enrollmentDate: new Date().toISOString().split('T')[0],
        email: email || '',
        guardianName: guardianName || '',
        guardianPhone: guardianPhone || '',
        guardianRelationship: guardianRelationship || '',
        grade: grade || '',
        major: major || '',
        department: department || ''
      };

      const createdStudent = studentModel.create(newStudent);

      if (createdStudent) {
        console.log('创建学生成功:', createdStudent);
        res.status(201).json(createdStudent);
      } else {
        res.status(500).json({ error: '保存失败' });
      }
    } catch (error) {
      console.error('创建学生失败:', error);
      res.status(500).json({ error: '创建失败' });
    }
  }
  // 获取用于成绩管理的学生列表
  async getStudentsForGrades(req, res) {
    try {
      console.log('获取用于成绩管理的学生列表');
      const students = studentModel.findAll();

      // 返回成绩管理需要的字段
      const gradeStudents = students.map(student => ({
        id: student.id,
        name: student.name,
        studentId: student.studentId,
        className: student.className,
        college: student.college,
        marketingDepartment: student.marketingDepartment,
        grade: student.grade,
        major: student.major,
        department: student.department
      }));

      console.log(`返回 ${gradeStudents.length} 个学生数据`);
      res.json(gradeStudents);
    } catch (error) {
      console.error('获取学生列表失败:', error);
      res.status(500).json({
        error: '获取学生列表失败',
        details: error.message
      });
    }
  }

  // 获取学生评语
  async getStudentComments(req, res) {
    try {
      const { id } = req.params;
      console.log('获取学生评语:', id);

      // 从文件中读取评语数据
      const allCommentsData = readData(studentCommentsFilePath, []);
      const commentsData = allCommentsData.find(item => item.studentId === parseInt(id));

      if (commentsData) {
        res.json(commentsData);
      } else {
        // 如果没有找到，返回空的评语数据结构
        const student = studentModel.findById(id);
        res.json({
          id: allCommentsData.length + 1,
          studentId: parseInt(id),
          studentNumber: student?.studentId || '',
          studentName: student?.name || '',
          className: student?.className || '',
          comments: []
        });
      }
    } catch (error) {
      console.error('获取学生评语失败:', error);
      res.status(500).json({ error: '获取评语失败' });
    }
  }

  // 添加学生评语
  async addStudentComment(req, res) {
    try {
      const { id } = req.params;
      const { stage, teacher, score, comment } = req.body;

      console.log('添加学生评语:', { id, stage, teacher });

      if (!stage || !teacher || !comment) {
        return res.status(400).json({ error: '阶段、讲师和评语为必填字段' });
      }

      // 从文件中读取评语数据
      const allCommentsData = readData(studentCommentsFilePath, []);
      const student = studentModel.findById(id);

      if (!student) {
        return res.status(404).json({ error: '学生不存在' });
      }

      // 查找或创建该学生的评语数据
      let studentCommentsData = allCommentsData.find(item => item.studentId === parseInt(id));

      if (!studentCommentsData) {
        // 创建新的学生评语数据
        studentCommentsData = {
          id: allCommentsData.length + 1,
          studentId: parseInt(id),
          studentNumber: student.studentId,
          studentName: student.name,
          className: student.className,
          comments: []
        };
        allCommentsData.push(studentCommentsData);
      } else {
        // 检查是否已存在该阶段的评语
        const existingComment = studentCommentsData.comments.find(c => c.stage === stage);
        if (existingComment) {
          return res.status(400).json({ error: `该学生的${stage}阶段评语已存在` });
        }
      }

      // 创建新评语
      const newComment = {
        stage,
        teacher,
        score: score || 0,
        comment,
        date: new Date().toISOString().split('T')[0]
      };

      // 添加到评语数组
      studentCommentsData.comments.push(newComment);

      // 保存到文件
      const saved = saveData(studentCommentsFilePath, allCommentsData);

      if (saved) {
        res.json({
          success: true,
          message: '评语保存成功',
          comment: newComment
        });
      } else {
        res.status(500).json({ error: '保存失败，请重试' });
      }
    } catch (error) {
      console.error('添加学生评语失败:', error);
      res.status(500).json({ error: '保存评语失败' });
    }
  }

  // 删除学生评语
  async deleteStudentComment(req, res) {
    try {
      const { id, stage } = req.params;
      console.log('删除学生评语:', { id, stage });

      // 从文件中读取评语数据
      const allCommentsData = readData(studentCommentsFilePath, []);
      const studentCommentsData = allCommentsData.find(item => item.studentId === parseInt(id));

      if (!studentCommentsData) {
        return res.status(404).json({ error: '未找到该学生的评语数据' });
      }

      // 查找要删除的评语
      const commentIndex = studentCommentsData.comments.findIndex(c => c.stage === stage);

      if (commentIndex === -1) {
        return res.status(404).json({ error: `未找到${stage}阶段的评语` });
      }

      // 删除评语
      studentCommentsData.comments.splice(commentIndex, 1);

      // 如果没有评语了，考虑是否从数组中移除该学生的数据
      // 这里保留学生数据结构，只清空评语数组

      // 保存到文件
      const saved = saveData(studentCommentsFilePath, allCommentsData);

      if (saved) {
        res.json({ success: true, message: '评语删除成功' });
      } else {
        res.status(500).json({ error: '删除失败，请重试' });
      }
    } catch (error) {
      console.error('删除学生评语失败:', error);
      res.status(500).json({ error: '删除评语失败' });
    }
  }

  // 获取评语阶段选项
  async getCommentStages(req, res) {
    try {
      const stages = [
        '专业一', '专业二', '专业三', '专业四', '专业五',
        '专高一', '专高二', '专高三', '专高四', '专高五', '专高六'
      ];

      res.json(stages);
    } catch (error) {
      console.error('获取阶段选项失败:', error);
      res.status(500).json({ error: '获取阶段选项失败' });
    }
  }

  // 导出学生数据
  async exportStudents(req, res) {
    try {
      const { format = 'excel' } = req.query;
      console.log('导出学生数据:', format);

      // 获取所有学生数据（应用搜索过滤）
      const students = studentModel.findAll();

      // 应用搜索过滤（与getStudents相同的逻辑）
      let filteredStudents = [...students];
      const searchFields = ['name', 'studentId', 'idCard', 'phone', 'className', 'college', 'marketingDepartment', 'dormBuilding', 'dormRoom', 'gender', 'status'];
      searchFields.forEach(field => {
        if (req.query[field] && req.query[field].trim()) {
          const searchValue = req.query[field].toLowerCase();
          filteredStudents = filteredStudents.filter(student => {
            const fieldValue = student[field];
            return fieldValue && fieldValue.toString().toLowerCase().includes(searchValue);
          });
        }
      });

      // 定义导出的列
      const headers = [
        '学号', '姓名', '性别', '出生日期', '身份证号',
        '市场部', '班级', '学院', '手机号',
        '宿舍楼', '宿舍号', '状态', '入学日期',
        '邮箱', '监护人姓名', '监护人电话', '监护人关系'
      ];

      const headerKeys = [
        'studentId', 'name', 'gender', 'birthDate', 'idCard',
        'marketingDepartment', 'className', 'college', 'phone',
        'dormBuilding', 'dormRoom', 'status', 'enrollmentDate',
        'email', 'guardianName', 'guardianPhone', 'guardianRelationship'
      ];

      // 准备导出数据
      const exportData = filteredStudents.map(student => {
        const row = {};
        headerKeys.forEach((key, index) => {
          let value = student[key] || '';
          // 状态转换
          if (key === 'status') {
            value = value === 'active' ? '在读' : value === 'suspended' ? '休学' : value === 'graduated' ? '已毕业' : value;
          }
          row[headers[index]] = value;
        });
        return row;
      });

      if (format === 'csv') {
        // 生成CSV
        let csv = headers.join(',') + '\n';
        exportData.forEach(row => {
          const values = headers.map(header => {
            const value = row[header] || '';
            // 处理包含逗号的值
            return value.includes(',') ? `"${value.replace(/"/g, '""')}"` : value;
          });
          csv += values.join(',') + '\n';
        });

        res.setHeader('Content-Type', 'text/csv; charset=utf-8');
        res.setHeader('Content-Disposition', `attachment; filename=students_export_${new Date().getTime()}.csv`);
        // 添加BOM以支持Excel正确显示中文
        res.write('\ufeff');
        res.end(csv);
      } else {
        // 生成Excel
        const worksheet = XLSX.utils.json_to_sheet(exportData);
        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, '学生列表');

        // 设置列宽
        const colWidths = headers.map(() => ({ wch: 15 }));
        worksheet['!cols'] = colWidths;

        const buffer = XLSX.write(workbook, {
          type: 'buffer',
          bookType: 'xlsx'
        });

        res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        res.setHeader('Content-Disposition', `attachment; filename=students_export_${new Date().getTime()}.xlsx`);
        res.send(buffer);
      }
    } catch (error) {
      console.error('导出学生数据失败:', error);
      res.status(500).json({ error: '导出失败', message: error.message });
    }
  }

  // 导入学生数据
  async importStudents(req, res) {
    try {
      console.log('导入学生数据');

      if (!req.file) {
        return res.status(400).json({ error: '请选择要导入的文件' });
      }

      const filePath = req.file.path;
      const fileExtension = path.extname(req.file.originalname).toLowerCase();

      let importData = [];

      // 根据文件类型解析
      if (fileExtension === '.csv') {
        // 读取CSV文件
        const fileContent = fs.readFileSync(filePath, 'utf-8');
        const lines = fileContent.split('\n').filter(line => line.trim());

        if (lines.length < 2) {
          fs.unlinkSync(filePath); // 删除临时文件
          return res.status(400).json({ error: '文件格式错误：至少需要表头和数据行' });
        }

        // 解析表头
        const headers = lines[0].split(',').map(h => h.trim().replace(/^"|"$/g, ''));

        // 解析数据行
        for (let i = 1; i < lines.length; i++) {
          const values = lines[i].split(',').map(v => v.trim().replace(/^"|"$/g, ''));
          if (values.length !== headers.length || !values[0]) continue; // 跳过空行

          const row = {};
          headers.forEach((header, index) => {
            row[header] = values[index] || '';
          });
          importData.push(row);
        }
      } else if (fileExtension === '.xlsx' || fileExtension === '.xls') {
        // 读取Excel文件
        const workbook = XLSX.readFile(filePath);
        const sheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[sheetName];
        importData = XLSX.utils.sheet_to_json(worksheet);
      } else {
        fs.unlinkSync(filePath); // 删除临时文件
        return res.status(400).json({ error: '不支持的文件格式，请使用CSV或Excel文件' });
      }

      // 删除临时文件
      fs.unlinkSync(filePath);

      if (importData.length === 0) {
        return res.status(400).json({ error: '文件中没有有效数据' });
      }

      // 字段映射（中文表头 -> 英文字段名）
      const fieldMapping = {
        '学号': 'studentId',
        '姓名': 'name',
        '性别': 'gender',
        '出生日期': 'birthDate',
        '身份证号': 'idCard',
        '市场部': 'marketingDepartment',
        '班级': 'className',
        '学院': 'college',
        '手机号': 'phone',
        '宿舍楼': 'dormBuilding',
        '宿舍号': 'dormRoom',
        '状态': 'status',
        '入学日期': 'enrollmentDate',
        '邮箱': 'email',
        '监护人姓名': 'guardianName',
        '监护人电话': 'guardianPhone',
        '监护人关系': 'guardianRelationship'
      };

      const details = [];
      let successCount = 0;
      let failedCount = 0;

      // 获取现有学生列表和班级列表
      const existingStudents = studentModel.findAll();
      const classes = classModel.findAll();

      // 处理每一行数据
      for (const row of importData) {
        try {
          // 转换字段名
          const studentData = {};
          Object.keys(row).forEach(key => {
            const mappedKey = fieldMapping[key] || key;
            studentData[mappedKey] = row[key];
          });

          // 验证必填字段
          if (!studentData.name || !studentData.studentId) {
            details.push({
              studentId: studentData.studentId || '未知',
              name: studentData.name || '未知',
              status: 'failed',
              message: '姓名和学号为必填字段'
            });
            failedCount++;
            continue;
          }

          // 检查学号是否已存在
          const existingStudent = existingStudents.find(s => s.studentId === studentData.studentId);
          if (existingStudent) {
            details.push({
              studentId: studentData.studentId,
              name: studentData.name,
              status: 'failed',
              message: '学号已存在'
            });
            failedCount++;
            continue;
          }

          // 验证班级是否存在
          if (studentData.className && !classes.find(c => c.className === studentData.className)) {
            details.push({
              studentId: studentData.studentId,
              name: studentData.name,
              status: 'failed',
              message: `班级 "${studentData.className}" 不存在`
            });
            failedCount++;
            continue;
          }

          // 状态值转换
          if (studentData.status) {
            const statusMap = {
              '在读': 'active',
              '休学': 'suspended',
              '已毕业': 'graduated',
              'active': 'active',
              'suspended': 'suspended',
              'graduated': 'graduated'
            };
            studentData.status = statusMap[studentData.status] || 'active';
          } else {
            studentData.status = 'active';
          }

          // 设置默认值
          studentData.enrollmentDate = studentData.enrollmentDate || new Date().toISOString().split('T')[0];

          // 创建学生
          const createdStudent = studentModel.create(studentData);

          if (createdStudent) {
            details.push({
              studentId: studentData.studentId,
              name: studentData.name,
              status: 'success',
              message: '导入成功'
            });
            successCount++;
            existingStudents.push(createdStudent); // 更新现有列表
          } else {
            details.push({
              studentId: studentData.studentId,
              name: studentData.name,
              status: 'failed',
              message: '保存失败'
            });
            failedCount++;
          }
        } catch (error) {
          details.push({
            studentId: row.studentId || row['学号'] || '未知',
            name: row.name || row['姓名'] || '未知',
            status: 'failed',
            message: error.message || '导入失败'
          });
          failedCount++;
        }
      }

      const result = {
        success: successCount > 0,
        message: `导入完成：成功 ${successCount} 条，失败 ${failedCount} 条`,
        details,
        total: importData.length,
        successCount,
        failedCount
      };

      res.json(result);
    } catch (error) {
      console.error('导入学生数据失败:', error);
      // 清理临时文件
      if (req.file && req.file.path) {
        try {
          fs.unlinkSync(req.file.path);
        } catch (e) {
          console.error('删除临时文件失败:', e);
        }
      }
      res.status(500).json({ error: '导入失败', message: error.message });
    }
  }

  // 下载导入模板
  async downloadImportTemplate(req, res) {
    try {
      const { format = 'csv' } = req.query;
      console.log('下载导入模板:', format);

      // 定义模板表头
      const headers = [
        '学号', '姓名', '性别', '出生日期', '身份证号',
        '市场部', '班级', '学院', '手机号',
        '宿舍楼', '宿舍号', '状态', '入学日期',
        '邮箱', '监护人姓名', '监护人电话', '监护人关系'
      ];

      // 添加示例数据行
      const exampleRow = [
        '2024001', '张三', '男', '2000-01-01', '110101200001011234',
        '保沧市场部', '2411A', '人工智能', '13800138000',
        '1号楼', '101', '在读', '2024-09-01',
        'zhangsan@example.com', '张父', '13900139000', '父亲'
      ];

      if (format === 'csv') {
        // 生成CSV模板
        let csv = headers.join(',') + '\n';
        csv += exampleRow.map(val => val.includes(',') ? `"${val}"` : val).join(',') + '\n';

        res.setHeader('Content-Type', 'text/csv; charset=utf-8');
        res.setHeader('Content-Disposition', `attachment; filename=student_import_template.csv`);
        // 添加BOM以支持Excel正确显示中文
        res.write('\ufeff');
        res.end(csv);
      } else {
        // 生成Excel模板
        const worksheet = XLSX.utils.aoa_to_sheet([
          headers,
          exampleRow
        ]);
        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, '学生导入模板');

        // 设置列宽
        const colWidths = headers.map(() => ({ wch: 15 }));
        worksheet['!cols'] = colWidths;

        const buffer = XLSX.write(workbook, {
          type: 'buffer',
          bookType: 'xlsx'
        });

        res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        res.setHeader('Content-Disposition', `attachment; filename=student_import_template.xlsx`);
        res.send(buffer);
      }
    } catch (error) {
      console.error('下载模板失败:', error);
      res.status(500).json({ error: '下载模板失败', message: error.message });
    }
  }
  // 更新学生
  async updateStudent(req, res) {
    try {
      const { id } = req.params;
      const {
        name,
        studentId,
        gender,
        birthDate,
        idCard,
        marketingDepartment,
        className,
        college,
        phone,
        dormBuilding,
        dormRoom,
        status,
        email,
        guardianName,
        guardianPhone,
        guardianRelationship,
        grade,
        major,
        department
      } = req.body;

      console.log('更新学生:', id, { name, studentId });

      const students = studentModel.findAll();

      // 检查学号是否被其他学生使用
      if (students.find(s => s.studentId === studentId && s.id !== parseInt(id))) {
        return res.status(400).json({ error: '学号已被其他学生使用' });
      }
      
      // 如果分配了宿舍，检查宿舍是否已满
      if (dormBuilding && dormRoom) {
        const dormitories = dormitoryModel.findAll();
        const dormitory = dormitories.find(d => 
          d.buildingName === dormBuilding && d.roomNumber === dormRoom
        );
        
        if (dormitory) {
          // 获取当前宿舍的现有成员（排除当前学生，因为可能是修改）
          const currentMembers = students.filter(student => 
            student.dormBuilding === dormBuilding && 
            student.dormRoom === dormRoom &&
            student.id !== parseInt(id) // 排除当前学生
          );
          
          // 如果宿舍已满（当前成员数 >= 最大容量），且当前学生不在这个宿舍中，则不允许分配
          const currentStudent = students.find(s => s.id === parseInt(id));
          const isCurrentDorm = currentStudent && 
            currentStudent.dormBuilding === dormBuilding && 
            currentStudent.dormRoom === dormRoom;
          
          if (!isCurrentDorm && currentMembers.length >= dormitory.totalBeds) {
            return res.status(400).json({ 
              error: `宿舍 ${dormBuilding} ${dormRoom} 已满（当前${currentMembers.length}人，最大容量${dormitory.totalBeds}人），无法分配` 
            });
          }
        }
      }

      const updatedStudent = studentModel.update(id, {
        name,
        studentId,
        gender: gender || '',
        birthDate: birthDate || '',
        idCard: idCard || '',
        marketingDepartment: marketingDepartment || '',
        className: className || '',
        college: college || '',
        phone: phone || '',
        dormBuilding: dormBuilding || '',
        dormRoom: dormRoom || '',
        status: status || 'active',
        email: email || '',
        guardianName: guardianName || '',
        guardianPhone: guardianPhone || '',
        guardianRelationship: guardianRelationship || '',
        grade: grade || '',
        major: major || '',
        department: department || ''
      });

      if (updatedStudent) {
        console.log('更新学生成功:', updatedStudent);
        res.json(updatedStudent);
      } else {
        res.status(404).json({ error: '学生不存在' });
      }
    } catch (error) {
      console.error('更新学生失败:', error);
      res.status(500).json({ error: '更新失败' });
    }
  }

  // 删除学生
  async deleteStudent(req, res) {
    try {
      const { id } = req.params;
      console.log('删除学生:', id);

      const success = studentModel.delete(id);

      if (success) {
        console.log('删除学生成功');
        res.json({ message: '删除成功' });
      } else {
        res.status(404).json({ error: '学生不存在' });
      }
    } catch (error) {
      console.error('删除学生失败:', error);
      res.status(500).json({ error: '删除失败' });
    }
  }
}
